<?php
/*
 * @Author: your name
 * @Date: 2021-05-20 10:19:39
 * @LastEditTime: 2021-05-20 11:19:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \myframe\app\Http\Controllers\Admin\LoginController.php
 */
namespace App\Http\Controllers\Admin;

use App\User;
use myframe\Captcha;

class LoginController extends CommonController
{
    protected $checkLoginExclude = ['index', 'login', 'captcha', 'logout'];

    public function index()
    {
        return $this->fetch('admin/login');
    }
    public function login(User $user)
    {
        //TODO:验证管理员的登录信息
        
        //  1、获取用户名、密码和验证码
        $username = $this->request->post('username', '');
        $password = $this->request->post('password', '');
        $captcha =  $this->request->post('captcha', '');

        //  2、验证验证码
        if (!$this->checkCaptcha($captcha)) {
            $this->error('登录失败：您输入的验证码有误！！');
        }

        //  3、 根据用户名查询数据库 验证用户名
        $userinfo=  $user->where('username', $username)->first();

        if (!$userinfo) {
            $this->error('用户不存在！！');
        }

        //   4、验证密码
        if ($userinfo['password'] != $this->passwordMD5($password, $userinfo['salt'])) {
            $this->error('用户名 或密码不正确！！');
        }
    
        //   5、保存登录态
        $this->setLogin(['id'=>$userinfo['id'],'name'=>$userinfo['username'],]);
        $this->success('登录成功！！');
    }

    protected function passwordMD5($password, $salt)
    {
        return md5(md5($password) . $salt);
    }

    protected function setLogin(array $user = [])
    {
        $_SESSION['cms']['admin'] = $user;
    }
    
    public function logout()
    {
        //TODO:实现管理员的退出登录
        
        //   1、清除Session信息
        $this->setLogin([]);
        //   2、重定向到登录页面
        $this->redirect('inedx');
    }

    public function captcha(Captcha $captcha)
    {
        $code = $captcha->create();
        $this->setCaptcha($code);
        $captcha->show($code);
    }
    protected function setCaptcha($code)
    {
        $_SESSION['cms']['captcha'] = $code;
    }

    protected function checkCaptcha($code)
    {
        if (isset($_SESSION['cms']['captcha'])) {
            $captcha = $_SESSION['cms']['captcha'];
            unset($_SESSION['cms']['captcha']);
            return strtolower($code) === strtolower($captcha);
        }
        return false;
    }
}
